package com.guomei.controller.exam;

import com.guomei.bean.exam.domain.ExamQuestion;
import com.guomei.service.exam.ExamQuestionService;
import com.guomei.utils.Result;
import com.guomei.utils.ValidationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.List;

/**
 * 考试题目控制器
 */
@RestController
@RequestMapping("/api1/examQuestion")
@Slf4j
public class ExamQuestionController {
    @Autowired
    private ExamQuestionService examQuestionService;

    /**
     * 获取题目信息
     * @return 题目列表
     */
    @PostMapping("/select")
    public Result<?> getAllQuestions(@RequestBody ExamQuestion examQuestion) {
        log.info("获取题目信息");
        try {
            if (examQuestion == null || examQuestion.getPageNum() == null || examQuestion.getPageSize() == null) {
                return Result.fail("分页字段信息缺失，查询失败");
            }
            // 验证分页参数是否有效
            if (examQuestion.getPageNum() <= 0 || examQuestion.getPageSize() <= 0) {
                return Result.fail("分页参数无效");
            }
            return examQuestionService.getByCondition(examQuestion);
        } catch (Exception e) {
            log.info("获取题目信息失败", e);
            return Result.fail("获取题目信息失败");
        }
    }

    /**
     * 根据ID获取题目详情
     * @param id 题目ID
     * @return 题目详情
     */
    @GetMapping("/detail/{id}")
    public Result<?> getQuestionDetail(@PathVariable Long id) {
        log.info("获取题目详情，ID：{}", id);
        try {
            if (id == null) {
                return Result.fail("题目ID不能为空");
            }
            ExamQuestion examQuestion = examQuestionService.getById(id);
            if (examQuestion == null) {
                return Result.fail("题目不存在");
            }
            return Result.success(examQuestion);
        } catch (Exception e) {
            log.info("获取题目详情失败", e);
            return Result.fail("获取题目详情失败");
        }
    }

    /**
     * 新增题目
     * @param examQuestion 题目信息
     * @return 新增结果
     */
    @PostMapping("/add")
    public Result<?> addQuestion(@Valid @RequestBody ExamQuestion examQuestion, BindingResult result) {
        log.info("新增题目入参：{}", examQuestion);
        //实体类注解参数校验
        Result commonDataResponse = ValidationUtil.validInputParams(result);
        if (commonDataResponse != null) {
            return commonDataResponse;
        }
        try {
            boolean success = examQuestionService.save(examQuestion);
            return success ? Result.success("新增成功") : Result.fail("新增失败");
        } catch (Exception e) {
            log.info("新增题目失败", e);
            return Result.error("新增失败");
        }
    }

    /**
     * 更新题目
     * @param examQuestion 题目信息
     * @return 更新结果
     */
    @PostMapping("/update")
    public Result<?> updateQuestion(@Valid @RequestBody ExamQuestion examQuestion, BindingResult result) {
        log.info("更新题目入参：{}", examQuestion);
        //实体类注解参数校验
        Result commonDataResponse = ValidationUtil.validInputParams(result);
        if (commonDataResponse != null) {
            return commonDataResponse;
        }
        try {
            if (examQuestion.getId() == null) {
                return Result.fail("题目ID不能为空");
            }
            boolean success = examQuestionService.update(examQuestion);
            return success ? Result.success("更新成功") : Result.fail("更新失败");
        } catch (Exception e) {
            log.info("更新题目失败", e);
            return Result.error("更新失败");
        }
    }

    /**
     * 删除题目
     * @param id 题目ID
     * @return 删除结果
     */
    @DeleteMapping("/delete/{id}")
    public Result<?> deleteQuestion(@PathVariable Long id) {
        log.info("删除题目，ID：{}", id);
        try {
            if (id == null) {
                return Result.fail("题目ID不能为空");
            }
            boolean success = examQuestionService.removeById(id);
            return success ? Result.success("删除成功") : Result.fail("删除失败");
        } catch (Exception e) {
            log.info("删除题目失败", e);
            return Result.fail("删除题目失败");
        }
    }

    /**
     * 根据考试ID获取题目列表
     * @param examId 考试ID
     * @return 题目列表
     */
    @GetMapping("/exam/{examId}")
    public Result<?> getQuestionsByExamId(@PathVariable Long examId) {
        log.info("根据考试ID获取题目列表，考试ID：{}", examId);
        try {
            if (examId == null) {
                return Result.fail("考试ID不能为空");
            }
            List<ExamQuestion> questions = examQuestionService.getByExamId(examId);
            return Result.success(questions);
        } catch (Exception e) {
            log.info("根据考试ID获取题目列表失败", e);
            return Result.fail("获取题目列表失败");
        }
    }

    /**
     * 根据考试ID和题目类型获取题目列表
     * @param examId 考试ID
     * @param questionType 题目类型
     * @return 题目列表
     */
    @GetMapping("/exam/{examId}/type/{questionType}")
    public Result<?> getQuestionsByExamIdAndType(@PathVariable Long examId, @PathVariable Short questionType) {
        log.info("根据考试ID和题目类型获取题目列表，考试ID：{}，题目类型：{}", examId, questionType);
        try {
            if (examId == null) {
                return Result.fail("考试ID不能为空");
            }
            if (questionType == null) {
                return Result.fail("题目类型不能为空");
            }
            List<ExamQuestion> questions = examQuestionService.getByExamIdAndType(examId, questionType);
            return Result.success(questions);
        } catch (Exception e) {
            log.info("根据考试ID和题目类型获取题目列表失败", e);
            return Result.fail("获取题目列表失败");
        }
    }

    /**
     * 通过Excel文件导入题目（第一个模板 - 客观题）
     * @param examId 考试ID
     * @param file Excel文件
     * @return 导入结果
     */
    @PostMapping("/importExcel/{examId}")
    public Result<?> importFromExcelFile(@PathVariable Long examId, @RequestParam("file") MultipartFile file) {
        log.info("通过Excel文件导入题目，考试ID：{}，文件名：{}", examId, file.getOriginalFilename());
        try {
            if (examId == null) {
                return Result.fail("考试ID不能为空");
            }
            if (file == null || file.isEmpty()) {
                return Result.fail("请选择要导入的Excel文件");
            }
            
            // 检查文件类型
            String fileName = file.getOriginalFilename();
            if (fileName == null || (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls"))) {
                return Result.fail("请上传Excel文件（.xlsx或.xls格式）");
            }
            
            Result<?> result = examQuestionService.importFromExcelFile(examId, file);
            
            // 确保文件流被正确关闭
            if (file.getInputStream() != null) {
                try {
                    file.getInputStream().close();
                } catch (Exception e) {
                    log.warn("关闭文件流时出现警告", e);
                }
            }
            
            return result;
        } catch (Exception e) {
            log.error("Excel文件导入失败", e);
            return Result.fail("Excel文件导入失败：" + e.getMessage());
        }
    }

    /**
     * 通过Excel文件导入主观题（第二个模板 - 主观题）
     * @param examId 考试ID
     * @param file Excel文件
     * @return 导入结果
     */
    @PostMapping("/importSubjectiveExcel/{examId}")
    public Result<?> importSubjectiveFromExcelFile(@PathVariable Long examId, @RequestParam("file") MultipartFile file) {
        log.info("通过Excel文件导入主观题，考试ID：{}，文件名：{}", examId, file.getOriginalFilename());
        try {
            if (examId == null) {
                return Result.fail("考试ID不能为空");
            }
            if (file == null || file.isEmpty()) {
                return Result.fail("请选择要导入的Excel文件");
            }
            
            // 检查文件类型
            String fileName = file.getOriginalFilename();
            if (fileName == null || (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls"))) {
                return Result.fail("请上传Excel文件（.xlsx或.xls格式）");
            }
            
            Result<?> result = examQuestionService.importSubjectiveFromExcelFile(examId, file);
            
            // 确保文件流被正确关闭
            if (file.getInputStream() != null) {
                try {
                    file.getInputStream().close();
                } catch (Exception e) {
                    log.warn("关闭文件流时出现警告", e);
                }
            }
            
            return result;
        } catch (Exception e) {
            log.error("主观题Excel文件导入失败", e);
            return Result.fail("主观题Excel文件导入失败：" + e.getMessage());
        }
    }

    /**
     * 根据考试ID删除所有题目
     * @param examId 考试ID
     * @return 删除结果
     */
    @DeleteMapping("/exam/{examId}/deleteAll")
    public Result<?> deleteAllQuestionsByExamId(@PathVariable Long examId) {
        log.info("根据考试ID删除所有题目，考试ID：{}", examId);
        try {
            if (examId == null) {
                return Result.fail("考试ID不能为空");
            }
            boolean success = examQuestionService.removeByExamId(examId);
            return success ? Result.success("删除成功") : Result.fail("删除失败");
        } catch (Exception e) {
            log.info("根据考试ID删除所有题目失败", e);
            return Result.fail("删除失败");
        }
    }

}
